package com.fick.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fick.hibernate.dao.ChannelDAO;
import com.fick.hibernate.dao.IpAllowedDAO;
import com.fick.hibernate.dao.IpAllowedStateDAO;
import com.fick.hibernate.model.Channel;
import com.fick.hibernate.model.IpAllowed;
import com.fick.hibernate.model.IpAllowedState;

public class IpFilter implements Filter, java.util.logging.Filter {

	public boolean checkIpFilter(ServletRequest request, HttpServletResponse respon) throws IOException {
		String curip = request.getRemoteAddr();
		if (curip != null) {
			String hql = "";
			IpAllowedDAO ipAllowedDao = new IpAllowedDAO();
			IpAllowed ipDb;
			List listAll = ipAllowedDao.findAll();
			ArrayList<String> listOne = new ArrayList<String>();
			ArrayList<String> listBtn = new ArrayList<String>();
			if (listAll != null && listAll.size() != 0) {
				for (int i = 0; i < listAll.size(); i++) {
					ipDb = (IpAllowed) listAll.get(i);
					if (ipDb.getIp().indexOf("-") == -1) {
						listOne.add(ipDb.getIp());
						continue;
					}
					listBtn.add(ipDb.getIp());
				}
			}
			String ipIn = "";
			if (listOne.size() != 0) {
				for (int i = 0; i < listOne.size(); i++) {
					ipIn = (String) listOne.get(i);
					if (ipIn.trim().equals(curip.trim())) {
						return true;
					}
				}
			}
			if (listBtn.size() != 0) {
				for (int i = 0; i < listBtn.size(); i++) {
					ipIn = (String) listBtn.get(i);
					String curips[] = curip.split("\\.");
					String ips[] = ipIn.split("-");
					String beginIp[] = ips[0].split("\\.");
					String endIp[] = ips[1].split("\\.");
					if (Integer.parseInt(curips[0].toString()) >= Integer.parseInt(beginIp[0].toString())
							&& Integer.parseInt(curips[0].toString()) <= Integer.parseInt(endIp[0].toString())
							&& Integer.parseInt(curips[1].toString()) >= Integer.parseInt(beginIp[1].toString())
							&& Integer.parseInt(curips[1].toString()) <= Integer.parseInt(endIp[1].toString())
							&& Integer.parseInt(curips[2].toString()) >= Integer.parseInt(beginIp[2].toString())
							&& Integer.parseInt(curips[2].toString()) <= Integer.parseInt(endIp[2].toString())
							&& Integer.parseInt(curips[3].toString()) >= Integer.parseInt(beginIp[3].toString())
							&& Integer.parseInt(curips[3].toString()) <= Integer.parseInt(endIp[3].toString())) {
						return true;
					}
				}
			}
		}
		return false;
		// 以下是原来的内容

		/*
		 * String curips[]=curip.split("\\."); String ips[]=chn.getPwd().split("-");
		 * String beginIp[]=ips[0].split("\\."); String endIp[]=ips[1].split("\\.");
		 * IpAllowedDAO ipDao = new IpAllowedDAO(); List list =
		 * ipDao.findByProperty("ip", curip); if(list != null && list.size() != 0 ){
		 * chain.doFilter(request, response); return; } if(curip!=null) {
		 * if(Integer.
		 * parseInt(curips[0].toString())>=Integer.parseInt(beginIp[0].toString())
		 * &&
		 * Integer.parseInt(curips[0].toString())<=Integer.parseInt(endIp[0].toString
		 * ())
		 * &&Integer.parseInt(curips[1].toString())>=Integer.parseInt(beginIp[1].
		 * toString()) &&
		 * Integer.parseInt(curips[1].toString())<=Integer.parseInt(endIp
		 * [1].toString())
		 * &&Integer.parseInt(curips[2].toString())>=Integer.parseInt
		 * (beginIp[2].toString()) &&
		 * Integer.parseInt(curips[2].toString())<=Integer
		 * .parseInt(endIp[2].toString())
		 * &&Integer.parseInt(curips[3].toString())>=Integer
		 * .parseInt(beginIp[3].toString()) &&
		 * Integer.parseInt(curips[3].toString())
		 * <=Integer.parseInt(endIp[3].toString()) ) { chain.doFilter(request,
		 * response); }else { respon.setCharacterEncoding("GBK");
		 * respon.getWriter().
		 * print("<script>alert('你无权访问该页面!�');location.href('index.jsp');</script>"
		 * ); } }
		 */
		// 以上是原来的内容
	}

	private void continueFilterChanneid(ServletRequest request, ServletResponse response, FilterChain chain,
			HttpServletRequest req, HttpServletResponse respon) throws IOException, ServletException {
		HttpSession se = req.getSession();
		/*
		 * ChannelDAO channelDao = new ChannelDAO(); Channel channel =
		 * channelDao.findById(194); if(channel.getPwd().trim().equals("1")){
		 * if(checkIpFilter(request,respon) == false)
		 * req.setAttribute("notemessage", "您无权查看！"); }
		 */
		if (req.getRequestURI().contains("contact")) {
			IpAllowedStateDAO ipDao = new IpAllowedStateDAO();
			List list = ipDao.findAll();
			if (list != null && list.size() != 0) {
				IpAllowedState ipState = (IpAllowedState) list.get(0);
				if (ipState.getState().trim().equals("1")) {
					if (checkIpFilter(request, respon) == false) {
						refuse(respon);
					}
					return;
				}
			}
		}

		if (request.getParameter("channelid") != null && !req.getRequestURI().contains(".do")
				&& !req.getRequestURI().contains("admin")) {
			ChannelDAO chnDAO = new ChannelDAO();
			Channel chn = chnDAO.findById(Integer.parseInt(request.getParameter("channelid")));
			if (chn.getPwd() != null && chn.getPwd().equals("1")) {
				if (checkIpFilter(request, respon) == true) {
					chain.doFilter(request, response);
				} else {
					refuse(respon);
				}
			} else {
				chain.doFilter(request, response);
			}

		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse respon = (HttpServletResponse) response;

		continueFilterChanneid(request, response, chain, req, respon);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

	@Override
	public boolean isLoggable(LogRecord record) {
		return false;
	}

	private void refuse(HttpServletResponse respon) throws IOException {
		respon.setCharacterEncoding("GBK");
		respon.getWriter().print("<script>alert('你无权访问该页面!�');location.href('index.jsp');</script>");
	}

}
